package com.lagou.rpc.consumer.controller;

import com.lagou.rpc.api.IUserService;
import com.lagou.rpc.consumer.ClientBootStrapApplication;
import com.lagou.rpc.consumer.client.RpcClient;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Desc
 * @Author Matures
 * @CreateTime 2021/4/12 22:47
 **/
@RestController
public class zookeeperController {


    @RequestMapping("/zkGetData")
    public String getData(){
        RpcClient rpcClient = getRpcClient();
        IUserService proxy = (IUserService) new RpcClientProxy(rpcClient).createZKProxy(IUserService.class);
        return proxy.getById(1).toString();
    }

    private RpcClient getRpcClient(){
        TreeMap<Integer,String> timesMap = new TreeMap<>();
        Map<String, RpcClient> maps = ClientBootStrapApplication.maps;
        for (Map.Entry<String, RpcClient> entry : maps.entrySet()) {
            // 读取节点数据的时间
            Object o = ClientBootStrapApplication.zkClient.readData(ClientBootStrapApplication.path + "/" + entry.getKey());
            timesMap.put(Integer.parseInt(o.toString().split(":")[2]),entry.getKey());
        }
        // 找到时间最小的RPCClient
        Object[] objects = timesMap.keySet().toArray();
        Arrays.sort(objects);
        RpcClient rpcClient = maps.get(timesMap.get(objects[0]));
        return rpcClient;
    }

}